package com.aurora.oa.message.view;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.aurora.oa.Constants.AuroraConstants;
import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.adapter.CommonRecyclerViewAdapter;
import com.aurora.oa.adapter.CommonRecyclerViewHolder;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.message.bean.MyReceiveMessageBean;
import com.aurora.oa.message.presenter.MessageListActivityPresenter;
import com.aurora.oa.message.presenter.MessageListActivityPresenterImpl;
import com.aurora.oa.utils.ToastUtil;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/24 0024.
 */
@SuppressWarnings("ResourceType")
public class MessageListActivity extends BaseActivity implements MessageListActivityView{
    LinearLayoutManager linearLayoutManager;
    private Handler handler = new Handler();
    boolean isLoading;
    private int whitchPage =1;
    int MessageType;
    RecyclerView rv_message_list;
    List<MyReceiveMessageBean> myReceiveMessageBeanList =new ArrayList<>();
    MessageListActivityPresenter messageListActivityPresenter;
    CommonRecyclerViewAdapter<MyReceiveMessageBean> commonRecyclerViewAdapter;
    SwipeRefreshLayout swipeRefreshLayout;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_message_list);
        messageListActivityPresenter = new MessageListActivityPresenterImpl(this);
        MessageType = getIntent().getIntExtra("message_type",-1);
        switch (MessageType){
            //集团消息
            case AuroraConstants.Message.GROUP_MESSAGE_TYPE:
                initTitlebar(true,"集团消息",true);
                break;
            //部门消息
            case AuroraConstants.Message.DEPART_MESSAGE_TYPE:
                initTitlebar(true,"部门消息",true);
                break;
            //个人消息
            case AuroraConstants.Message.PERSON_MESSAGE_TYPE:
                initTitlebar(true,"个人",true);
                break;
            default:
                initTitlebar(true,"错误类型",true);
                break;
        }

        swipeRefreshLayout =(SwipeRefreshLayout)  findViewById(R.id.SwipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.blue,R.color.white);
        messageListActivityPresenter.getMessageData(MessageType,whitchPage);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        whitchPage = 1;
                        myReceiveMessageBeanList.clear();
                        messageListActivityPresenter.getMessageData(MessageType,whitchPage);
                    }
                }, 0);
            }
        });

        rv_message_list = (RecyclerView) findViewById(R.id.rv_message_list);
        commonRecyclerViewAdapter = new CommonRecyclerViewAdapter<MyReceiveMessageBean>(this,myReceiveMessageBeanList) {
            @Override
            public void convert(CommonRecyclerViewHolder h, MyReceiveMessageBean entity, int position) {
                //未读
                if (entity.state ==1){
                    h.setTextColor(R.id.tv_status,Color.parseColor(getString(R.color.red)));
                    h.setText(R.id.tv_status,"未读");
                }else{
                    h.setTextColor(R.id.tv_status,Color.parseColor(getString(R.color.text_gray)));
                    h.setText(R.id.tv_status,"已读");
                }
                h.setText(R.id.tv_name,entity.fromUserName);
                h.setText(R.id.tv_duty,entity.fromUserPostName);
                h.setText(R.id.tv_title,entity.title);
                h.setText(R.id.tv_time,entity.sendtime+"");
                switch (MessageType){
                    //集团消息
                    case AuroraConstants.Message.GROUP_MESSAGE_TYPE:
                        h.setImage(R.id.sdv_head_img,R.mipmap.ico_message_jt);

                        break;
                    //部门消息
                    case AuroraConstants.Message.DEPART_MESSAGE_TYPE:
                        h.setImage(R.id.sdv_head_img,R.mipmap.ico_message_bm);
                        break;
                    //个人消息
                    case AuroraConstants.Message.PERSON_MESSAGE_TYPE:
                        h.setImageURL(R.id.sdv_head_img,AuroraConstants.BASE_SERVER_URL+"/"+entity.fromUserHeadImage);
                        break;
                    default:

                        break;
                }


            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_message_list;
            }
        };

      linearLayoutManager = new LinearLayoutManager(this);
        rv_message_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

               loadMoreData();
            }
        });
        rv_message_list.setLayoutManager(linearLayoutManager);
        rv_message_list.setAdapter(commonRecyclerViewAdapter);
        rv_message_list.addItemDecoration(new ItemDivider().setDividerWith(6).setDividerColor(Color.TRANSPARENT));
        commonRecyclerViewAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                ToastUtil.show(MessageListActivity.this,position+"");
            }
        });
    }

    @Override
    public void showMessageList(List<MyReceiveMessageBean> messageList) {
        myReceiveMessageBeanList.clear();
        myReceiveMessageBeanList.addAll(messageList);
        commonRecyclerViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRequestDataFail() {
        ToastUtil.show(this,"网络请求失败！");

    }

    @Override
    public void doPullDownRefresh(List<MyReceiveMessageBean> datas) {
        swipeRefreshLayout.setRefreshing(false);
        myReceiveMessageBeanList.addAll(datas);
        if(commonRecyclerViewAdapter.getFootCounts()>0){
            commonRecyclerViewAdapter.removeFootView(0,false);
            commonRecyclerViewAdapter.addFootView(View.inflate(this,R.layout.item_foot,null));
        }
        commonRecyclerViewAdapter.notifyDataSetChanged();
        //防止页数太少不加载了，滑动的时候会自动判断，判断静止的时候就自己去加载了，0表示不滑动了
        if(rv_message_list.getScrollState()==0){
            loadMoreData();
        }
    }

    private void loadMoreData() {
        int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
        if (lastVisibleItemPosition + 1 == commonRecyclerViewAdapter.getItemCount()) {
            Log.d("test", "loading executed");

            boolean isRefreshing = swipeRefreshLayout.isRefreshing();
            if (isRefreshing) {
                commonRecyclerViewAdapter.notifyItemRemoved(commonRecyclerViewAdapter.getItemCount());
                return;
            }
            if (!isLoading) {
                isLoading = true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        whitchPage +=1;
                        if(commonRecyclerViewAdapter.getFootCounts()>0){
                            commonRecyclerViewAdapter.removeFootView(0,false);
                            commonRecyclerViewAdapter.addFootView(View.inflate(MessageListActivity.this,R.layout.item_foot,null));
                        }else{
                            commonRecyclerViewAdapter.addFootView(View.inflate(MessageListActivity.this,R.layout.item_foot,null));
                        }
                        commonRecyclerViewAdapter.notifyDataSetChanged();
                        messageListActivityPresenter.getMessageData(MessageType,whitchPage);
                        Log.d("test", "load more completed");
                    }
                }, 0);
            }
        }
    }

    @Override
    public void doPullUpLoad(List<MyReceiveMessageBean> datas) {
        swipeRefreshLayout.setRefreshing(false);
        isLoading = false;
        if(datas==null||datas.size()==0){
            if(commonRecyclerViewAdapter.getFootCounts()>0){
                commonRecyclerViewAdapter.removeFootView(0,false);
                commonRecyclerViewAdapter.addFootView(View.inflate(this,R.layout.item_foot_null,null));
            }
            ;
        }else{
            myReceiveMessageBeanList.addAll(datas);
        }
        commonRecyclerViewAdapter.notifyDataSetChanged();
    }
}
